﻿using System;
using System.Web;

namespace MvcStarterKit.Infrastructure
{
	public class NHibernateModule: IHttpModule
	{
		private static bool _startupComplete = false;
		private static readonly object _locker = new object();

		public void Init(HttpApplication context)
		{
			context.BeginRequest += Context_BeginRequest;
			context.EndRequest += Context_EndRequest;
		}

		/// <summary>
		/// Starting a new NHibernate ISession with default transaction.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void Context_BeginRequest(object sender, EventArgs e)
		{
			EnsureStartup();
			new AppConfig().StartSession();
		}


		/// <summary>
		/// Ending any open ISession and commit active transaction
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private static void Context_EndRequest(object sender, EventArgs e)
		{
			new AppConfig().EndSession();
		}


		private void EnsureStartup()
		{
			if(!_startupComplete)
			{
				lock (_locker)
				{
					if(!_startupComplete)
					{
						new AppConfig().PerformStartup();
						_startupComplete = true;
					}
				}
			}
		}

		public void Dispose()
		{
			//...
		}
	}
}
